package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamService paramService;

    @Override
    public List<SpecGroupDTO> queryGroupParams(Long id) {
        //根据category的id查询规格组
        List<SpecGroup> specGroupList = query().eq("category_id", id).list();
        //判断该分类id是否有对应的规格组
        if (CollectionUtils.isEmpty(specGroupList)) {
            //没有
            return null;
        }
        //转换
        List<SpecGroupDTO> specGroupDTOList = SpecGroupDTO.convertEntityList(specGroupList);
      /*  //遍历集合
        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {
            //获取id
            Long specGroupDTOId = specGroupDTO.getId();
            //获取规格参数奇数
            //List<SpecParam> specParams = paramService.query().eq("group_id", specGroupDTOId).list();
            List<SpecParamDTO> specParamDTOS = paramService.querySpecParamsByCondition(null, specGroupDTOId, null);
            //转换后赋值
            //specGroupDTO.setParams(SpecParamDTO.convertEntityList(specParams));
            specGroupDTO.setParams(specParamDTOS);
        }*/
        //查询所有规格参数
        List<SpecParamDTO> specParamDTOList = paramService.querySpecParamsByCondition(id, null, null);
       /* //创建一个空Map
        Map<Long, List<SpecParamDTO>> map = new HashMap<>();
        //遍历集合
        for (SpecParamDTO specParamDTO : specParamDTOList) {
            //获取组id
            Long groupId = specParamDTO.getGroupId();
            //判断该key是否存在
            if (!map.containsKey(groupId)) {
                //不存在需要新建
                map.put(groupId,new ArrayList<>());
            }
            //添加
            map.get(groupId).add(specParamDTO);
        }*/
        //规格参数按groupId分组
        Map<Long, List<SpecParamDTO>> map = specParamDTOList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        //遍历group集合，添加规格参数
        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {
            //根据groupID从map中获取参数集合
            specGroupDTO.setParams(map.get(specGroupDTO.getId()));
        }
        return specGroupDTOList;
    }
}